package com.hjq.mallcart.intercepter;

/**
 * @auther HJQ
 */

import com.hjq.common.constants.AuthConstants;
import com.hjq.common.constants.CartConstants;
import com.hjq.common.entity.vo.UserAccountVO;
import com.hjq.mallcart.entity.UserInfoVO;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.UUID;

/**
 * 判断用户状态，并封装传递给Controller
 */

public class CartIntercepter implements HandlerInterceptor {
    public static ThreadLocal<UserInfoVO> threadLocal=new ThreadLocal<>();
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //无论等没登陆，都要有UserKey
        UserInfoVO userInfoVO = new UserInfoVO();

        HttpSession session = request.getSession();
        UserAccountVO loginInfo = (UserAccountVO)session.getAttribute(AuthConstants.LOGIN_USER);
        if(loginInfo!=null){
            //登陆l
            userInfoVO.setUserId(loginInfo.getId());
        }
        Cookie[] cookies = request.getCookies();
        if(cookies!=null&&cookies.length>0){
            for (Cookie cookie : cookies) {
                String name = cookie.getName();
                if(name.equals(CartConstants.USER_KEY)){
                    userInfoVO.setUserKey(cookie.getValue());
                    userInfoVO.setHasKey(true);
                }
            }
        }
        //如果没有临时用户
        if(StringUtils.isEmpty(userInfoVO.getUserKey())){
            String uuid= UUID.randomUUID().toString();
            userInfoVO.setUserKey(uuid);
        }
        //放在ThreadLocal中放进去
        threadLocal.set(userInfoVO);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView)  {
        Cookie cookie = new Cookie(CartConstants.USER_KEY,threadLocal.get().getUserKey());
        if(!threadLocal.get().getHasKey()){
            cookie.setDomain("hjqmall.com");
            cookie.setMaxAge(CartConstants.OUTDATE_TIME);
            response.addCookie(cookie);
        }

    }
}
